package com.xmb.wpclient.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmb.wpclient.constant.LayTableR;
import com.xmb.wpclient.constant.R;
import com.xmb.wpclient.entity.SysDept;
import com.xmb.wpclient.entity.SysRole;
import com.xmb.wpclient.entity.SysUser;
import com.xmb.wpclient.service.ISysDeptService;
import com.xmb.wpclient.service.ISysRoleService;
import com.xmb.wpclient.service.ISysUserService;
import com.xmb.wpclient.utils.ConditionUtil;
import com.xmb.wpclient.utils.MD5;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
	
	@Autowired
	private ISysUserService iSysUserService;
	
	@Autowired
	private ISysRoleService iSysRoleService;
	
	@Autowired
	private ISysDeptService iSysDeptService;

	@RequestMapping("/index")
	public String index(Model model) {
		model.addAttribute("deptList", iSysDeptService.list());
		model.addAttribute("roleList", iSysRoleService.list());
		return "user/index";
	}
	
	@RequestMapping("/updatePwdHtml")
	public String updatePwdHtml() {
		return "user/updatePwd";
	}
	
	@RequestMapping("/addHtml")
	public String addHtml(Model model) {
		model.addAttribute("deptList", iSysDeptService.list());
		model.addAttribute("roleList", GetRoleChildren(null));
		return "user/add";
	}

//	@RequestMapping("/deptList")
//	@ResponseBody
//	public Object deptList() {
//		return GetChildren(null);
//	}
	
	@RequestMapping("/roleList")
	@ResponseBody
	public Object roleList() {
		return GetRoleChildren(null);
	}
	
	@RequestMapping("/updateHtml")
	public String updateHtml(Model model,String id) {
		SysUser user = iSysUserService.selectInfoOne(new QueryWrapper<SysUser>().eq("id", id));
		user.setUserPassword("");
		model.addAttribute("user", user);
		model.addAttribute("deptList", iSysDeptService.list());
		return "user/update";
	}
	
	@PostMapping("/list")
	@ResponseBody
	public LayTableR list(Integer page, Integer limit, String master, String dept, String role) {
		
		QueryWrapper<SysUser> ew = null;
		IPage<SysUser> selectPage = null;
		try {
			ew = ConditionUtil.convert(master, new QueryWrapper<SysUser>());
			selectPage = iSysUserService.selectInfoPage(new Page<SysUser>(page, limit), ew, dept, role);
		} catch (Exception e) {
			e.printStackTrace();
		}
		for (SysUser sysUser : selectPage.getRecords()) {
			SysDept sysDept = iSysDeptService.getById(sysUser.getDepartmentId());
			sysUser.setDepartmentName(sysDept.getDeptName());
			sysUser.setUserPassword("");
			sysUser.setRoleName(iSysRoleService.selectInfoOne(new QueryWrapper<SysRole>().eq("id", sysUser.getRoleId())).getRoleName());
		}
		
		return LayTableR.result(0, selectPage.getTotal(), selectPage.getRecords());
	}

	@PostMapping("/add")
	@ResponseBody
	public R add(SysUser user) {
		//初始密码设为123456
		String password = "123456";
		//将用户编码与密码一起MD5加密
		user.setUserPassword(MD5.toMD5PWD(user.getUserCode(), password));
		try {
			SysUser selectUser = iSysUserService.selectInfoOne(new QueryWrapper<SysUser>().eq("user_code", user.getUserCode()));
			if(selectUser != null) {
				return R.error("用户编码已存在");
			}
			iSysUserService.add(user);
		} catch (Exception e) {
			log.error("添加用户", e);
			return R.error("系统异常");
		}
		return R.ok();
	}

	@PostMapping("/update")
	@ResponseBody
	public R update(SysUser user) {
		try {
			iSysUserService.edit(user);
		} catch (Exception e) {
			log.error("修改用户", e);
			return R.error("系统异常");
		}
		return R.ok();
	}

	@PostMapping("/delete")
	@ResponseBody
	public R update(@RequestBody List<String> ids) {
		try {
			iSysUserService.deleteInfo(ids);
		} catch (Exception e) {
			log.error("删除用户", e);
			return R.error("系统异常");
		}
		return R.ok();
	}

	@PostMapping("/pwd_reset")
	@ResponseBody
	public R pwd_reset(String id) {
		try {
			SysUser sysUser = iSysUserService.getById(id);
			if(sysUser == null) {
				return R.error("用户不存在");
			}
			sysUser.setUserPassword(MD5.toMD5PWD(sysUser.getUserCode(), "123456"));
			iSysUserService.updateById(sysUser);
		} catch (Exception e) {
			log.error("重置用户密码", e);
			return R.error("系统异常");
		}
		return R.ok();
	}
	
	@RequestMapping("/basic")
	public String basic(Model model) {
		//获取当前用户
		SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
		user.setUserPassword(null);
		model.addAttribute("user", user);
		return "user/basic";
	}
	
	@PostMapping("/updatePwd")
	@ResponseBody
	public R updatePwd(String oldpwd,String newpwd) {
		try {
			//获取当前用户
			SysUser user = null;
			user = (SysUser) SecurityUtils.getSubject().getPrincipal();
			Long userId = user.getId();
			user = iSysUserService.selectInfoOne(new QueryWrapper<SysUser>().eq("id", userId));
			if(!MD5.toMD5PWD(user.getUserCode(), oldpwd).equals(user.getUserPassword())) {
				return R.error("原密码错误");
			}
			user.setUserPassword(MD5.toMD5PWD(user.getUserCode(), newpwd));
			iSysUserService.edit(user);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error();
		}
		return R.ok();
	}
	
//	public List<Map<String, Object>> GetChildren(String pid,List<Map<String, Object>> data) {
//		Map<String,Object> map = null;
//		List<SysDept> childredPermissions = null;
//		if(StringUtils.isEmpty(pid)) {
//			childredPermissions = iSysDeptService.selectInfoList(new QueryWrapper<SysDept>().and(wrapper -> wrapper.eq("pid", "")).or().isNull("pid").or().eq("pid","0"));
//		}else {
//			childredPermissions = iSysDeptService.selectInfoList(new QueryWrapper<SysDept>().eq("pid", pid));
//		}
//		for (SysDept sysDept : childredPermissions) {
//			map = new HashMap<String, Object>();
//			map.put("id", sysDept.getId());
//			map.put("pid", sysDept.getPid()==null?"0":sysDept.getPid());
//			map.put("name", sysDept.getDeptName());
//			map.put("code", sysDept.getDeptCode());
//			data.add(map);
//			long count = iSysDeptService.selectInfoCount(new QueryWrapper<SysDept>().eq("pid", sysDept.getId()));
//			if(count != 0) {
//				data = GetChildren(sysDept.getId(), data);
//			}
//		}
//		return data;
//	}
	
//	public List<Map<String, Object>> GetChildren(String pid) {
//		List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();
//		Map<String,Object> map = null;
//		List<SysDept> childredPermissions = null;
//		if(StringUtils.isEmpty(pid)) {
//			childredPermissions = iSysDeptService.selectInfoList(new QueryWrapper<SysDept>().and(wrapper -> wrapper.eq("pid", "")).or().isNull("pid").or().eq("pid","0"));
//		}else {
//			childredPermissions = iSysDeptService.selectInfoList(new QueryWrapper<SysDept>().eq("pid", pid));
//		}
//		for (SysDept sysDept : childredPermissions) {
//			map = new HashMap<String, Object>();
//			map.put("id", sysDept.getId());
//			map.put("name", sysDept.getDeptName());
//			map.put("open", true);
//			long count = iSysDeptService.selectInfoCount(new QueryWrapper<SysDept>().eq("pid", sysDept.getId()));
//			if(count != 0) {
//				map.put("children", GetChildren(sysDept.getId()));
//			}
//			data.add(map);
//		}
//		return data;
//	}
	
	public List<Map<String, Object>> GetRoleChildren(String pid) {
		List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();
		Map<String,Object> map = null;
		List<SysRole> childredPermissions = null;
		if(StringUtils.isEmpty(pid)) {
			childredPermissions = iSysRoleService.selectInfoList(new QueryWrapper<SysRole>().and(wrapper -> wrapper.eq("pid", "")).or().isNull("pid").or().eq("pid","0"));
		}else {
			childredPermissions = iSysRoleService.selectInfoList(new QueryWrapper<SysRole>().eq("pid", pid));
		}
		for (SysRole sysRole : childredPermissions) {
			map = new HashMap<String, Object>();
			map.put("id", sysRole.getId());
			map.put("name", sysRole.getRoleName());
			map.put("open", true);
			long count = iSysRoleService.selectInfoCount(new QueryWrapper<SysRole>().eq("pid", sysRole.getId()));
			if(count != 0) {
				map.put("children", GetRoleChildren(sysRole.getId().toString()));
			}
			data.add(map);
		}
		return data;
	}
	
//	public StringBuffer getSupper(String id,StringBuffer res) {
//		if(StringUtils.isEmpty(id)) {
//			return res;
//		}
//		SysDept sysDept = iSysDeptService.selectInfo(new QueryWrapper<SysDept>().eq("id", id));
//		res.insert(0, sysDept.getDeptName()+"/");
//		if(sysDept != null) {
//			res = getSupper(sysDept.getPid(),res);
//		}
//		return res;
//	}
}